package com.springboot.ball.controller.user.account;

import com.springboot.ball.service.impl.utils.UserDetailsImpl;
import com.springboot.ball.service.user.account.UpdateUserPhotoService;
import com.springboot.ball.utils.AliyunOSSOperator;
import com.springboot.ball.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
@Slf4j
@RestController
public class UpdateUserPhotoController {
    @Autowired
    private UpdateUserPhotoService UpdateUserPhotoService;
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    @PostMapping("/user/account/upload/")
    public Result upload(MultipartFile file) {
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
            // 上传文件
            String url = null;

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            Integer userId = userDetails.getUser().getId();
            try {
                url = aliyunOSSOperator.upload(file.getBytes(), uniqueFileName);
                log.info("上传文件{}", file);
                return UpdateUserPhotoService.updateUserPhoto(userId, url);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return Result.error("上传失败");
    }
}
